package org.epam.szhuk.greenway.activity;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.epam.szhuk.greenway.R;
import org.epam.szhuk.greenway.adapter.SelectSpeedFileAdapter;
import org.epam.szhuk.greenway.asynctask.LoadLocationDataTask;
import org.epam.szhuk.greenway.model.LocationFileSelection;
import org.epam.szhuk.greenway.model.StoredGeoPoint;
import org.epam.szhuk.greenway.util.FileProcessor;
import org.epam.szhuk.greenway.util.GeoDataProcessor;
import org.epam.szhuk.greenway.util.NetworkSender;
import org.epam.szhuk.greenway.util.Preferences;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Toast;

public class SelectLocationFilesActivity extends ListActivity {
	private static final String TAG = "SelectLocationFilesActivity";
	private static final int CONTEXTMENU_TICK=201;
	private static final int CONTEXTMENU_DELETE=202;
	private Button buttonBuildSpeedgraph;
	private Button buttonSendToServer;
   // private Button buttonCancel;
    private List<LocationFileSelection> listFiles = new ArrayList<LocationFileSelection>();
   // private Preferences prefs;
    
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.activity_select_speedfiles);
		listFiles=loadFileList();
		ArrayAdapter<LocationFileSelection> adapter = new SelectSpeedFileAdapter(
				this, listFiles);
		setListAdapter(adapter);
		
		buttonBuildSpeedgraph = (Button) findViewById(R.id.button_show_on_map);
		buttonBuildSpeedgraph.setOnClickListener(new OnClickListener() {
 			@Override
 			public void onClick(View v) {
 				buttonShowSelectedClick(v);
 			}
 		});

		buttonSendToServer = (Button) findViewById(R.id.button_send_to_server);
		buttonSendToServer.setOnClickListener(new OnClickListener() {
 			@Override
 			public void onClick(View v) {
 				buttonSendToServerClick(v);
 			}
 		});

		ListView list = this.getListView();
		 registerForContextMenu(list);
	}

	private void buttonSendToServerClick(View v){
		NetworkSender.sendToServer(this, null);
	}
	
	private void buttonShowSelectedClick(View v){
		
		List<String> listSelectedFiles = new ArrayList<String>();	
  		for(int i=listFiles.size()-1; i>-1;i--){ //back sort to save order by date
  			if(listFiles.get(i).isSelected()){
  				listSelectedFiles.add(listFiles.get(i).getFullPath());
  			}
  		}

		LoadLocationDataTask loadLocationDataTask =new LoadLocationDataTask(this, listSelectedFiles); 
		loadLocationDataTask.execute();	
	}
	
	private void myToast(String text) {
		Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
	}
	
	private List<LocationFileSelection> loadFileList() {
		
		Preferences prefs=new Preferences(this);
		List<LocationFileSelection> listResult = new ArrayList<LocationFileSelection>();
		Log.w(TAG, listResult.toString());
		String speedDirPath=Environment.getExternalStorageDirectory()+File.separator+prefs.getAppFilesFolder()+File.separator;
		File folderDirPath = new File(speedDirPath);
		if(!folderDirPath.exists()){
			folderDirPath.mkdir();
		}
		File[] files = folderDirPath.listFiles();
		Log.w(TAG, files.toString());
		if(files!=null){
			Arrays.sort(files,Collections.reverseOrder());
			for (int i = 0; i < files.length; i++) {
				File file = files[i];
				if (file.canRead()) { // adding to listFiles only files that could be
										// accessed by our app
					if ((!file.isDirectory()) && (file.getName().endsWith("txt"))) {
						String fileCaptionDate=file.getName().substring(0, file.getName().lastIndexOf('.'));
						SimpleDateFormat sdfFromFile = new SimpleDateFormat(Preferences.DATE_SAVE_MEDIAFILE_FORMAT);
				        Date date;
						try {
							date = sdfFromFile.parse(fileCaptionDate);
							SimpleDateFormat sdfDisplay = new SimpleDateFormat(Preferences.DATE_TITLE_FOR_SELECT_SPEEDFILE_FORMAT,java.util.Locale.getDefault());
							fileCaptionDate=sdfDisplay.format(date);
						}catch (ParseException e) {
							Log.e(TAG,"Wrong date in line (parsing failed): "+fileCaptionDate, e);					
						}
						
						LocationFileSelection spFileSelection = new LocationFileSelection(fileCaptionDate,file.getAbsolutePath());
						listResult.add(spFileSelection);
					}
				}
			}
			//updateFileListAdapter(listVideoData.getListItems());
		}else{
			Log.e(TAG, "File listFiles is NULL");
			myToast("Can't get access to the listFiles of recorded speed files");
		}
		return listResult;
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		menu.add(Menu.NONE, CONTEXTMENU_TICK, 0, R.string.context_select);
		menu.add(Menu.NONE, CONTEXTMENU_DELETE, 0, R.string.context_delete);
		String fileName = listFiles.get(info.position).getFullPath();//check path
		menu.setHeaderTitle(getResources().getString(R.string.file)+": "+fileName);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		String selectedFilePath = "";
		try {
			selectedFilePath = listFiles.get(info.position).getFullPath();
		} catch (IndexOutOfBoundsException e) {
			Log.e(TAG, "IndexOutOfBoundsException: ", e);
			myToast("IndexOutOfBoundsException during file from list selection");
			return false;
		}
		switch (item.getItemId()) {
		case CONTEXTMENU_TICK:
			int pos= info.position;
			clickListElement(pos);
			updateList();
			break;
		case CONTEXTMENU_DELETE:
			delSpeedFile(selectedFilePath);
			break;
		default:
			Log.e(TAG, "Unexpected menu id");
		}
		return true;
	}
	
	/**
	 * 
	 * @param path path of file to delete
	 */
	private void delSpeedFile(String path){
		final File file = new File(path);
		if ((file.exists()) && (file.canRead())) {	
			Context context= getBaseContext();
			AlertDialog.Builder builder=new AlertDialog.Builder(this);
			builder.setTitle(R.string.app_name);
			builder.setMessage(getResources().getString(R.string.delete_file)+" \""+file.getName()+ "\" ?");
		    builder.setPositiveButton(context.getString(android.R.string.ok),new DialogInterface.OnClickListener(){
		    	public void onClick(DialogInterface dialog,int id){
					if(file.delete()){
						listFiles.remove(file.getName());
						FileProcessor.removeFile(file);
						listFiles=loadFileList();
						updateList();
					}
					else {
						Log.e(TAG, "File " + file.getAbsolutePath()
								+ " can't be deleted");
						myToast(getResources().getString(R.string.file)+" " + file.getAbsolutePath() +" "
								+ getResources().getString(R.string.cant_be_deleted));
						return;
					}
		    	}
		    });
		                 
		    builder.setNegativeButton(context.getString(android.R.string.cancel),new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog,int id){
					dialog.cancel();
			    }
			});
		    builder.setCancelable(false);
		    builder.create();
			builder.show();
			
		} else {
			Log.e(TAG, "File " + file.getAbsolutePath() + " doesn't exists or can't be read");
			myToast("File " + file.getAbsolutePath() + "  doesn't exists or can't be read");
		}
	}
	private void updateList(){
		ListView listView = this.getListView();
		int index = listView.getFirstVisiblePosition();
		ArrayAdapter<LocationFileSelection> adapter = new SelectSpeedFileAdapter(this, listFiles);
		setListAdapter(adapter);
		listView.setSelection(index);
	}
	
	private void clickListElement(int pos){
		listFiles.get(pos).setSelected(!listFiles.get(pos).isSelected());
	}

}